<#systemSituation globalInfo="${globalInfo}"/>
<link rel="stylesheet" href="/static/css/metroStyle.css">
<!-- 防止页面数据重复定义,模板数据统一在此 -->
<!--:
    var typeList = dicttag.getDictList('sys_user_type');
    var ableList = dicttag.getDictList('yes_no');
    var sexList = dicttag.getDictList('sex');
    var typeJson = commontag.toJson(typeList);
    var sexJson = commontag.toJson(sexList);
    var ableJson = commontag.toJson(ableList);
    var isAdmin = usertag.isAdmin();
    var roleJson = commontag.toJson(usertag.getRoleList());
-->

<!-- widget grid with search -->
<section>

    <!-- row -->
    <div class="row">

        <!-- NEW WIDGET START -->
        <article class="col-xs-12 col-sm-12 col-md-12 col-lg-12">

            <div class="jarviswidget jarviswidget-color-blueDark" data-widget-editbutton="false">
                <header>
                    <span class="widget-icon"> <i class="fa fa-table"></i> </span>

                    <h2>用户列表 </h2>

                </header>

                <div>

                    <!-- widget edit box -->
                    <div class="jarviswidget-editbox">
                        <!-- This area used as dropdown edit box -->
                    </div>
                    <!-- end widget edit box -->

                    <div class="alert alert-block  search-alert">
                        <form id="query-form" action="" class="form-horizontal">
                            <header class="search-header">
                                <a class="close txt-color-greenLight search-action"
                                   href="javascript:"><i
                                        class="fa fa-hand-o-down"></i></a>
                                <h4 class="alert-heading">
                                    <i class="fa fa-search txt-color-greenLight search-title"></i>&nbsp;&nbsp;查询过滤
                                </h4>
                            </header>
                            <div class="search-div hide">

                                <fieldset>
                                    <legend>
                                    </legend>

                                    <div class="row" style="margin: 0 20px">

                                        <div class="col-sm-4">

                                            <div class="form-group" style="padding: 5px 25px">
                                                <div class="input-group" rel="tooltip"
                                                     data-placement="top"
                                                     data-original-title="根据用户的部门进行查询">
                                                    <span class="input-group-addon"><i
                                                            class="fa fa-home"></i></span>
                                                    <div id="parent-office"></div>
                                                </div>
                                            </div>

                                        </div>
                                        <div class="col-sm-4" style="padding: 5px 25px">

                                            <div class="input-group" rel="tooltip"
                                                 data-placement="top"
                                                 data-original-title="用户的登录名">
                                                <span class="input-group-addon"><i
                                                        class="fa fa-user"></i></span>
                                                <input type="text" name="loginName"
                                                       class="form-control" style="">
                                            </div>
                                        </div>

                                        <div class="col-sm-4" style="padding: 5px 25px">

                                            <div class="input-group" rel="tooltip"
                                                 data-placement="top"
                                                 data-original-title="用户的邮件信息中包含的内容">
                                                <span class="input-group-addon"><i
                                                        class="fa fa-envelope-o"></i></span>
                                                <input type="text" name="email" class="form-control"
                                                       style="">
                                            </div>
                                        </div>

                                    </div>
                                </fieldset>

                                <div class="form-actions search-footer">
                                    <div class="row">
                                        <div class="col-md-12">
                                            <button type="button" name="query"
                                                    class="btn btn-primary">
                                                <i class="fa fa-search"></i> 查询
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                        <script type="text/javascript">
                            $(function () {
                                var $form = $('#query-form');
                                $form.find('.search-action, .search-title')
                                        .on('click', function () {
                                            var search_div = $form.find('.search-div');
                                            if (search_div.hasClass('hide')) {
                                                search_div.removeClass('hide');
                                                $form.find('.search-action').find('i').removeClass()
                                                        .addClass('fa fa-hand-o-left');
                                            } else {
                                                search_div.addClass('hide');
                                                $form.find('.search-action').find('i').removeClass()
                                                        .addClass('fa fa-hand-o-down');
                                            }
                                        });
                            });
                        </script>
                    </div>

                    <!-- widget content -->
                    <div class="widget-body no-padding">
                        <div id="userTable"></div>
                    </div>

                </div>
            </div>

        </article>
        <!-- WIDGET END -->
    </div>
    <!-- end row -->
</section>
<!-- end widget grid with search -->

<!-- office tree -->
<div id="office-tree-dialog"></div>
<div id="office-sel-tree-dialog"></div>
<!-- end office tree -->

<!-- assign role user -->
<div id="assign-user-role" class="well dialog-well" style="display: none;">
    <!-- widget content -->
    <div class="alert alert-block alert-success">
        <h4 class="alert-heading role-assign"></h4>
        <p>
            通过双向选择器为用户分配角色.
        </p>
    </div>
    <div class="">
        <select multiple="multiple" id="assignDuallistbox">
        </select>
    </div>
    <!-- end widget content -->
</div>
<!-- end assign role user -->

<!-- user form content -->
<div class="well dialog-well" id="user-dialog" style="display: none;">

    <div class="widget-body no-padding">

        <form id="user-form" action="${ctx}/sys/user/save" method="post" class="smart-form">

            <fieldset>
                <div class="hide">
                    <input type="hidden" name="id"> 　
                </div>
                <section>
                    <label class="label">所属机构</label>
                    <div id="office"></div>
                </section>
                <section>
                    <label class="label">登录名称</label>
                    <label class="input">
                        <i class="icon-append fa fa-key"></i>
                        <input name="oldLoginName" type="hidden">
                        <input type="text" name="loginName" placeholder="admin">
                        <b class="tooltip tooltip-bottom-right">用户的登录名称,必须设置</b>
                    </label>
                </section>
                <div class="row">
                    <section class="col col-6">
                        <label class="label">密码</label>
                        <label class="input">
                            <input type="password" id="newPassword" name="newPassword"
                                   placeholder="">
                            <b class="tooltip tooltip-bottom-right">若不修改密码，请留空</b>
                        </label>
                        <div class="progress" style="margin-bottom: 1px;">
                            <div id="newPasswordBar" class="progress-bar" role="progressbar">
                            </div>
                        </div>
                    </section>
                    <section class="col col-6">
                        <label class="label">确认密码</label>
                        <label class="input">
                            <input id="confirmNewPassword" type="password" name="confirmNewPassword" placeholder="">
                            <b class="tooltip tooltip-bottom-right">需要与密码输入保存一致</b>
                        </label>
                        <div class="progress" style="margin-bottom: 1px;">
                            <div id="confirmNewPasswordBar" class="progress-bar" role="progressbar">
                            </div>
                        </div>
                    </section>
                </div>
                <div class="row">
                    <section class="col col-6">
                        <label class="label">显示名称</label>
                        <label class="input">
                            <i class="icon-append fa fa-user"></i>
                            <input type="text" name="name" placeholder="用户显示的名称(管理员)">
                            <b class="tooltip tooltip-bottom-right">用户显示的名称,必须设置</b>
                        </label>
                    </section>
                    <section class="col col-6">
                        <label class="label">工号</label>
                        <label class="input">
                            <i class="icon-append fa fa-openid"></i>
                            <input type="text" name="no" placeholder="10000">
                            <b class="tooltip tooltip-bottom-right">用户的工号,用户工作流的标识</b>
                        </label>
                    </section>
                </div>

                <div class="row">
                    <section class="col col-6">
                        <label class="label">性别</label>
                        <label class="select" rel="tooltip" data-placement="bottom"
                               data-original-title='用户的性别'>
                            <select name="sex">
                                <!--:
                                    for(sex in sexList!){
                                -->
                                <option value="${sex.value!''}">${sex.label!''}</option>
                                <!--:
                                    }
                                -->
                            </select><i></i>
                        </label>
                    </section>
                    <section class="col col-6">
                        <label class="label">年龄</label>
                        <label class="input">
                            <i class="icon-append fa fa-signing"></i>
                            <input type="text" name="age" placeholder="18">
                            <b class="tooltip tooltip-bottom-right">用户的年龄</b>
                        </label>
                    </section>
                </div>

                <section>
                    <label class="label">邮箱</label>
                    <label class="input">
                        <i class="icon-append fa fa-envelope-o"></i>
                        <input name="email" type="text" placeholder="zeyuphoenix@163.com">
                        <b class="tooltip tooltip-bottom-right">用户的邮件地址</b>
                    </label>
                </section>

                <div class="row">
                    <section class="col col-6">
                        <label class="label">电话</label>
                        <label class="input">
                            <i class="icon-append fa fa-phone"></i>
                            <input type="text" name="mobile" placeholder="010-23456789">
                            <b class="tooltip tooltip-bottom-right">用户的电话</b>
                        </label>
                    </section>
                    <section class="col col-6">
                        <label class="label">手机</label>
                        <label class="input">
                            <i class="icon-append fa fa-mobile"></i>
                            <input type="text" name="phone" placeholder="18555445588">
                            <b class="tooltip tooltip-bottom-right">用户的手机号码</b>
                        </label>
                    </section>
                </div>

                <section>
                    <label class="label">是否允许登录</label>
                    <label class="select" rel="tooltip" data-placement="bottom"
                           data-original-title='“是”代表此账号允许登录，“否”则表示此账号不允许登录'>
                        <select name="loginFlag">
                            <!--:
                                for(able in ableList!){
                            -->
                            <option value="${able.value!''}">${able.label!''}</option>
                            <!--:
                                }
                            -->
                        </select><i></i>
                    </label>
                </section>

                <section>
                    <label class="label">用户类型</label>
                    <label class="select" rel="tooltip" data-placement="bottom"
                           data-original-title='用户的类型选择'>
                        <select name="type">
                            <!--:
                                for(type in typeList!){
                            -->
                            <option value="${type.value!''}">${type.label!''}</option>
                            <!--:
                                }
                            -->
                        </select><i></i>
                    </label>
                </section>

                <section>
                    <label class="label">用户角色</label>
                    <select name="roleIdList" multiple style="width:100%" class="select2">
                        <!--:
                              for(role in allRoles!){
                          -->
                        <option value="${role.id!''}">${role.name!''}</option>
                        <!--:
                            }
                        -->
                    </select>
                </section>

                <section>
                    <label class="label">备注信息</label>
                    <label class="textarea">
                        <i class="icon-append fa fa-comment"></i>
                        <textarea rows="4" name="remarks"></textarea>
                    </label>
                </section>

                <div id="userInfo" style="display: none;">
                    <div class="row">
                        <section class="col col-6">
                            <label class="label">创建者</label>
                            <label class="input state-disabled">
                                <i class="icon-append fa fa-gift"></i>
                                <input type="text" name="createName" disabled="disabled">
                                <b class="tooltip tooltip-bottom-right">创建者</b>
                            </label>
                        </section>
                        <section class="col col-6">
                            <label class="label">创建时间</label>
                            <label class="input state-disabled">
                                <i class="icon-append fa fa-calendar-plus-o"></i>
                                <input type="text" name="createDate" disabled="disabled">
                                <b class="tooltip tooltip-bottom-right">用户的工号,用户工作流的标识</b>
                            </label>
                        </section>
                    </div>
                    <div class="row">
                        <section class="col col-6">
                            <label class="label">最后登录地址</label>
                            <label class="input state-disabled">
                                <i class="icon-append fa fa-map-marker"></i>
                                <input type="text" name="loginIp" disabled="disabled">
                                <b class="tooltip tooltip-bottom-right">用户最后登录的地址</b>
                            </label>
                        </section>
                        <section class="col col-6">
                            <label class="label">最后登录时间</label>
                            <label class="input state-disabled">
                                <i class="icon-append fa fa-calendar"></i>
                                <input type="text" name="loginDate" disabled="disabled">
                                <b class="tooltip tooltip-bottom-right">用户最后登录的时间</b>
                            </label>
                        </section>
                    </div>
                </div>

            </fieldset>

        </form>

    </div>
</div>
<!-- end user form content -->


<script type="text/javascript">

    /* DO NOT REMOVE : GLOBAL FUNCTIONS!
     *
     * pageSetUp(); WILL CALL THE FOLLOWING FUNCTIONS
     *
     * // activate tooltips
     * $("[rel=tooltip]").tooltip();
     *
     * // activate popovers
     * $("[rel=popover]").popover();
     *
     * // activate popovers with hover states
     * $("[rel=popover-hover]").popover({ trigger: "hover" });
     *
     * // activate inline charts
     * runAllCharts();
     *
     * // setup widgets
     * setup_widgets_desktop();
     *
     * // run form elements
     * runAllForms();
     *
     ********************************
     *
     * pageSetUp() is needed whenever you load a page.
     * It initializes and checks for all basic elements of the page
     * and makes rendering easier.
     *
     */
    pageSetUp();

    /*
     * ALL PAGE RELATED SCRIPTS CAN GO BELOW HERE
     */
    // PAGE RELATED SCRIPTS
    // pagefunction
    var pagefunction = function () {

        var params = {};
        var $userFrom = $("#user-form");
        var $queryFrom = $("#query-form");
        $userFrom.validate({
            // Rules for form validation
            rules: {
                // 为了不污染html代码,验证统一在js中
                'parent.name': {
                    required: true
                },
                loginName: {
                    required: true,
                    maxlength: 50,
                    userName: true,
                    remote: {
                        url: "${ctx}/sys/user/checkLoginName",
                        type: "post",
                        data: {
                            'oldLoginName': function () {
                                return $userFrom.find('input[name=oldLoginName]')
                                        .val();
                            },
                            'loginName': function () {
                                return $userFrom.find('input[name=loginName]')
                                        .val();
                            }
                        }
                    }
                },
                no: {
                    required: true,
                    maxlength: 20
                },
                name: {
                    required: true,
                    maxlength: 50
                },
                newPassword: {
                    minlength: 4,
                    maxlength: 50
                },
                confirmNewPassword: {
                    minlength: 4,
                    maxlength: 50,
                    equalTo: '#newPassword'
                },
                email: {
                    maxlength: 100,
                    email: true
                },
                age: {
                    digits: true,
                    maxlength: 3
                },
                phone: {
                    mobile: true
                },
                mobile: {
                    simplePhone: true
                },
                roleIdList: {
                    required: true
                },
                remarks: {
                    maxlength: 250
                }
            },
            // Messages for form validation,use default
            messages: {
                // 不覆盖使用默认js多语言文件
                loginName: {remote: "用户登录名已存在"},
                confirmNewPassword: {equalTo: "输入与上面相同的密码"},
                roleIdList: {required: '必须指定用户角色'}
            },
            submitHandler: function (form) {
                // 遮罩
                var loadIndex = parent.layer.load(0, {shade: 0.4});

                $(form).ajaxSubmit({
                    dataType: "json",
                    success: function (data) {
                        parent.layer.close(loadIndex);

                        if (data && data.status
                                == 'success') {
                            // .dt-toolbar .dt_refresh .dt-refresh-btn
                            parent.$(
                                    '#userTable .dt-toolbar .dt-refresh-btn')
                                    .trigger('click');
                            parent.messageBox(data.message,
                                    "success");
                        } else {
                            parent.messageBox(data.message,
                                    "error");
                        }
                        // 显示
                        parent.layer.closeAll('page');
                    },
                    error: function () {
                        parent.layer.close(loadIndex);
                        parent.messageBox("修改用户错误!", "error");
                    }
                });
                // always return false to prevent standard browser submit and page navigation
                return false;
            },
            // Do not change code below
            errorPlacement: function (error, element) {
                error.insertAfter(element.parent());
            }
        });

        /**
         * 根据类型获取类型label
         * @param value 类型value
         * @param type 类型
         */
        function getLabel(value, type) {
            var dicts = [];
            if (type == 1) {
                dicts = eval('${typeJson!""}');
            } else if (type == 2) {
                dicts = eval('${sexJson!""}');
            } else {
                dicts = eval('${ableJson!""}');
            }
            // 设置默认显示type
            var label = value;
            if (dicts) {
                $.each(dicts, function (i, dict) {
                    if (dict['value'] == value) {
                        label = dict['label'];
                        return false;
                    }
                });
            }
            return label;
        }

        var datatable = new DataTableData({
                    databind: $('#userTable').get(0),
                    //数据请求url地址
                    dataurl: '${ctx}/sys/user/list',
                    //数据请求参数
                    params: params,
                    hasCache: true,
                    hasCheck: true,
                    info: false,
                    checkBind: 'id',
                    toolbarStates: {
                        "add": {
                            action: function () {
                                form();
                            }
                        },
                        "edit": {
                            action: function () {
                                var selDatas = datatable.getSelectedDatas();
                                if (selDatas && selDatas.length > 0) {
                                    modifyUser(selDatas[0]['id']);
                                }
                            }
                        },
                        "delete": {
                            mult: false,   // 不允许多选删除
                            action: function () {
                                var selDatas = datatable.getSelectedDatas();
                                if (selDatas && selDatas.length > 0) {
                                    var id = selDatas[0]['id'];
                                    layer.confirm('您真的要删除选择的数据？', {
                                                icon: 3,
                                                title: '删除角色',
                                                btn: ['确定', '取消'], //按钮
                                                shade: 0.4 //不显示遮罩
                                            }, function (index) {
                                                // send
                                                ajaxCoomand({
                                                    url: '${ctx}/sys/user/delete',
                                                    data: {id: id},
                                                    callback: function () {
                                                        datatable.refresh();
                                                    }
                                                });

                                                layer.close(index);
                                            }
                                    );
                                }
                            }
                        }
                    },
                    columns: [
                        {data: "office\\.name", title: '归属部门'},
                        {
                            data: 'loginName', title: '登录名称',
                            render: function (data, type, row) {
                                return '<a href="javascript:" onclick="modifyUser(' + "'" + row['id'] + "'"
                                        + ')">' + data + '</a>';
                            }
                        },
                        {data: 'name', title: '显示名称'},
                        {
                            data: 'type', title: '类型',
                            render: function (value) {
                                return '<div class="text-center">' + getLabel(value, 1) + '</div>';
                            }
                        },
                        {
                            data: 'loginFlag', title: '允许登录',
                            render: function (value) {
                                return '<div class="text-center"><span class="label label-default">' + getLabel(value, 3) + '</span></div>';
                            }
                        },
                        {data: 'email', title: '邮件地址'},
                        {
                            data: 'id',
                            title: '操作',
                            render: function (data) {
                                return '<a href="javascript:" class="btn btn-warning" style="padding: 0 5px;" onclick="assign('
                                        + "'" + data + "'" + ')"><i class="fa fa-deaf"></i> 分配角色</a>';
                            }
                        }
                    ]
                }
        );

        /**
         * 打开编辑框
         */
        function form(user) {
            var opr = '添加';
            if (user != null && !$.isEmptyObject(user) && user['id'] != null) {
                opr = "修改";
            }
            // 添加修改对话框
            layer.open({
                type: 1,
                title: opr + '用户',
                shadeClose: false,
                shade: 0.4,
                area: ['720px', '600px'],   //高度自动适应
                maxmin: true,
                content: $('#user-dialog'),
                btn: ['确定', '取消'],
                success: function () {
                    // 当你需要在层创建完毕时即执行一些语句，可以通过该回调。success会携带两个参数，分别是当前层DOM当前层索引
                    // 这里可以通过发送ajax获取,也可通过表格选择时获取的行的值设置
                    var value = '1';
                    var labelValue = '总公司';
                    $userFrom.find('input[name=newPassword]')
                            .rules("add", {required: true});
                    if (user != null && !$.isEmptyObject(user)) {
                        if (user['id'] != null) {
                            $userFrom.find('input[name=id]').val(user['id']);
                            $userFrom.find('input[name=newPassword]')
                                    .rules("remove", 'required');
                        }
                        $userFrom.find('input[name="office.id"]').val(user['office.id']);
                        $userFrom.find('input[name=name]').val(user['name']);
                        $userFrom.find('input[name=loginName]').val(user['loginName']);
                        $userFrom.find('input[name=oldLoginName]').val(user['loginName']);
                        $userFrom.find('select[name=type]').val(user['type']);
                        $userFrom.find('input[name=no]').val(user['no']);
                        $userFrom.find('select[name=sex]').val(user['sex']);
                        $userFrom.find('input[name=age]').val(user['age']);

                        $userFrom.find('input[name=email]').val(user['email']);
                        $userFrom.find('input[name=mobile]').val(user['mobile']);
                        $userFrom.find('input[name=phone]').val(user['phone']);
                        $userFrom.find('select[name=loginFlag]').val(user['loginFlag']);
                        $userFrom.find('textarea[name=remarks]').val(user['remarks']);
                        $userFrom.find('#userInfo').show();
                        $userFrom.find('input[name=createName]').val(user['createName']);
                        $userFrom.find('input[name=createDate]').val(user['createDate']);
                        $userFrom.find('input[name=loginIp]').val(user['loginIp']);
                        $userFrom.find('input[name=loginDate]').val(user['loginDate']);
                        $userFrom.find('select[name=roleIdList]').select2()
                                .val(user['roleIdList']).trigger("change");

                        value = user['office.id'];
                        labelValue = user['office.name'];
                    }
                    // 需要根据选择设置树
                    addTreeSelect.refresh({
                        value: value,
                        labelValue: labelValue
                    });
                },
                end: function () {
                    // 无论是确认还是取消，只要层被销毁了，end都会执行，不携带任何参数
                    $userFrom.find('input[name=id]').val('');
                    $userFrom.find('input[name="office.id"]').val('');
                    $userFrom.find('input[name=name]').val('');
                    $userFrom.find('input[name=loginName]').val('');
                    $userFrom.find('input[name=oldLoginName]').val('');
                    $userFrom.find('select[name=type]').get(0).selectedIndex = 0;
                    $userFrom.find('input[name=newPassword]').val('');
                    $userFrom.find('input[name=confirmNewPassword]').val('');
                    $userFrom.find('input[name=no]').val('');
                    $userFrom.find('select[name=sex]').get(0).selectedIndex = 0;
                    $userFrom.find('input[name=age]').val('');
                    $userFrom.find('input[name=email]').val('');
                    $userFrom.find('input[name=mobile]').val('');
                    $userFrom.find('input[name=phone]').val('');
                    $userFrom.find('select[name=loginFlag]').get(0).selectedIndex = 0;
                    $userFrom.find('textarea[name=remarks]').val('');
                    $userFrom.find('input[name=createName]').val('');
                    $userFrom.find('input[name=createDate]').val('');
                    $userFrom.find('input[name=loginIp]').val('');
                    $userFrom.find('input[name=loginDate]').val('');
                    $userFrom.find('select[name=roleIdList]').select2().val(null).trigger("change");
                    $userFrom.find('#userInfo').hide();
                    $userFrom.find('input[name=newPassword]').rules("remove", 'required');
                },
                yes: function () { //或者使用btn1
                    // 按钮【确定】的回调
                    $userFrom.submit();
                },
                cancel: function (index) { //或者使用btn2
                    // 按钮【取消】的回调
                    layer.close(index);
                }
            });
        }

        /**
         * 分配角色
         */
        function assign(id) {

            // 添加修改对话框
            layer.open({
                type: 1,
                title: "分配角色",
                shadeClose: false,
                shade: 0.4,
                area: ['640px', '552px'],   //高度因为双选框首次自适应不准确,暂时设置高度
                maxmin: true,
                content: $('#assign-user-role'),
                btn: ['确定', '取消'],
                success: function () {
                    // 获取当前用户信息
                    $.ajax({
                        url: '${ctx}/sys/user/infoData',
                        data: {id: id},
                        type: 'post',
                        success: function (data) {
                            if (data) {
                                $('#assign-user-role').find('.role-assign')
                                        .html("<i class='fa fa-check-square-o'></i> 用户名: "
                                                + data['name'] + "");
                            }
                        }
                    });

                    // 获取用户角色列表
                    $.ajax({
                        url: '${ctx}/sys/user/userRoles',
                        data: {id: id},
                        type: 'post',
                        async: false,
                        success: function (data) {
                            var selDatas = [];
                            if (data && data.length > 0) {
                                // 点击展示下属用户
                                $.each(data, function (index, val) {
                                    selDatas.push(val['id']);
                                    $('#assignDuallistbox').append(
                                            '<option value="' + val['id']
                                            + '" selected>' + val['name']
                                            + '</option>');
                                });
                            }

                            var allRoles = eval('${roleJson!"[]"}');
                            if (allRoles && allRoles != '' && allRoles.length
                                    > 0) {
                                // 展示角色
                                $.each(allRoles, function (index, val) {
                                    if (selDatas && selDatas.length > 0) {
                                        // 去除已经选择的
                                        if (selDatas.indexOf(val['id']) < 0) {
                                            $('#assignDuallistbox').append(
                                                    '<option value="' + val['id']
                                                    + '">' + val['name']
                                                    + '</option>');
                                        }
                                    } else {
                                        $('#assignDuallistbox').append(
                                                '<option value="' + val['id']
                                                + '">' + val['name']
                                                + '</option>');
                                    }
                                });
                            }

                            $('#assignDuallistbox').bootstrapDualListbox('refresh');
                        }
                    });
                },
                end: function () {
                    // 清除左右菜单
                    $('#assignDuallistbox').find('option').remove();
                    $('#assignDuallistbox').bootstrapDualListbox('refresh');
                },
                yes: function (index) { //或者使用btn1
                    // 按钮【确定】的回调
                    var $assignDuallistbox = $('#assignDuallistbox');
                    var selIds = $assignDuallistbox.val();
                    ajaxCoomand({
                        url: '${ctx}/sys/user/assign',
                        data: {id: id, roleIds: selIds}
                    });
                    layer.close(index);
                },
                cancel: function (index) { //或者使用btn2
                    // 按钮【取消】的回调
                    layer.close(index);
                }
            });
        }

        /**
         * 修改用户
         */
        function modifyUser(id) {
            var user = null;

            // 获取当前用户信息
            $.ajax({
                url: '${ctx}/sys/user/infoData',
                data: {id: id},
                type: 'post',
                async: false,
                dataType: 'json',
                success: function (data) {
                    if (data) {
                        user = data;
                    }
                }
            });

            if (user != null) {
                user['office.id'] = user['office.id'];
                if (user['office.name'] == null) {
                    user['office.name'] = "总公司"
                } else {
                    user['office.name'] = user['office.name'];
                }
            }
            form(user);
        }

        /**
         * 初始化一个tree selecter, 之后通过refresh设置值
         */
        new TreeSelecter({
            databind: $('#parent-office').get(0),
            // 对话框弹出对话框需要外部定义一个div
            databind_dialog: $('#office-sel-tree-dialog').get(0),
            title: '区域',
            name: 'office.id',
            // 隐藏域值
            value: '0',
            // 输入框名称
            labelName: 'office.name',
            // 输入框值
            labelValue: '',
            // 数据请求url地址,树结构数据地址
            dataurl: '${ctx}/sys/office/treeData',
            // 根据当前用户是否是admin角色决定
            allowClear: true
        });

        /**
         * 初始化一个tree selecter, 之后通过refresh设置值
         */
        var addTreeSelect = new TreeSelecter({
            databind: $('#office').get(0),
            // 对话框弹出对话框需要外部定义一个div
            databind_dialog: $('#office-tree-dialog').get(0),
            title: '区域',
            name: 'office.id',
            // 隐藏域值
            value: '0',
            // 输入框名称
            labelName: 'office.name',
            // 输入框值
            labelValue: '',
            // 数据请求url地址,树结构数据地址
            dataurl: '${ctx}/sys/office/treeData',
            // 根据当前用户是否是admin角色决定
            allowClear: true
        });

        // 密码强度组件
        loadScript("/static/js/plugin/complexify/jquery.complexify.js", initComplexify);
        function initComplexify() {
            $("#newPassword").complexify({minimumChars: 4}, function (valid, complexity) {
                var progressBar = $('#newPasswordBar');

                progressBar.toggleClass('progress-bar-success', valid);
                progressBar.toggleClass('progress-bar-danger', !valid);
                progressBar.css({'width': complexity + '%'});
            });
            $("#confirmNewPassword").complexify({minimumChars: 4}, function (valid, complexity) {
                var progressBar = $('#confirmNewPasswordBar');

                progressBar.toggleClass('progress-bar-success', valid);
                progressBar.toggleClass('progress-bar-danger', !valid);
                progressBar.css({'width': complexity + '%'});
            });
        }

        /*
         * BOOTSTRAP DUALLIST BOX
         */
        loadScript("/static/js/plugin/bootstrap-duallistbox/jquery.bootstrap-duallistbox.js", initDuallistbox);
        // 初始化用户->角色配置选中组件
        function initDuallistbox() {
            $('#assignDuallistbox').bootstrapDualListbox({
                nonSelectedListLabel: '未分配角色',
                selectedListLabel: '已分配角色',
                preserveSelectionOnMove: '移动',
                filterPlaceHolder: '过滤',
                filterTextClear: '显示所有',
                infoTextEmpty: '无角色',
                infoText: '总共有 {0}',
                moveSelectedLabel: '移动选择项',
                moveAllLabel: '移动所有',
                removeSelectedLabel: '删除选择项',
                removeAllLabel: '删除所有',
                moveOnSelect: false,
                selectorMinimalHeight: '180',
                nonSelectedFilter: ''
            });
        }

        // query
        $queryFrom.find('[name=query]').on('click', function () {
            params = {
                "office.id": $queryFrom.find('input[name="office.id"]').val(),
                loginName: $queryFrom.find('input[name=loginName]').val(),
                email: $queryFrom.find('input[name=email]').val()
            };
            // 根据查询更新表
            datatable.refresh(params);
        });

        // 密码回显
        password_feedback($userFrom, initComplexify);
        // 注册
        window.assign = assign;
        window.modifyUser = modifyUser;

    };

    // destroy generated instances
    // pagedestroy is called automatically before loading a new page
    // only usable in AJAX version!
    var pagedestroy = function () {
        // 移除注册方法
        window.assign = undefined;
        window.modifyUser = undefined;
        $('#assignDuallistbox').bootstrapDualListbox('destroy');
    };
    // end destroy

    // load related plugins
    loadScript("/static/js/plugin/jquery-tree/jquery.ztree.all-3.5.js", function () {
        loadScript("/static/js/plugin/jquery-tree/jquery.ztree.exhide-3.5.js", function () {
            loadScript("/static/js/extend/TreeSelecter.js", function () {
                loadScript("/static/js/plugin/datatables/jquery.dataTables.js", function () {
                    loadScript("/static/js/plugin/datatables/dataTables.colVis.js", function () {
                        loadScript("/static/js/plugin/datatables/dataTables.tableTools.js", function () {
                            loadScript("/static/js/plugin/datatables/dataTables.bootstrap.js", function () {
                                loadScript("/static/js/plugin/datatable-responsive/datatables.responsive.js", function () {
                                    loadScript("/static/js/plugin/jquery-form/jquery.form.js");
                                    loadScript("/static/js/extend/DataTableData.js", pagefunction);
                                });
                            });
                        });
                    });
                });
            });
        });
    });

</script>